package pe.edu.upc.dsd.jjjar.upcbank.client.mvc.layouts;

import java.util.List;

import pe.edu.upc.dsd.jjjar.upcbank.client.AfiliacionServiceAsync;
import pe.edu.upc.dsd.jjjar.upcbank.client.AfiliacionView;
import pe.edu.upc.dsd.jjjar.upcbank.client.BancoUPC;
import pe.edu.upc.dsd.jjjar.upcbank.resources.client.Resources;
import pe.edu.upc.dsd.jjjar.upcbank.resources.client.model.Afiliacion;
import pe.edu.upc.dsd.jjjar.upcbank.resources.client.model.Cuenta;
import pe.edu.upc.dsd.jjjar.upcbank.resources.client.model.Operation;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class AfiliacionNueva extends LayoutContainer {

	private VerticalPanel vp;
	private ContentPanel contentPanel;
	private final AfiliacionServiceAsync service = (AfiliacionServiceAsync) Registry.get(BancoUPC.AFILIACION_SERVICE);
	private FormPanel form;

	private ComboBox<Cuenta> cboCuenta;
	private NumberField numCelular;
	private TextField<String> txtFrase;
	private TextField<String> txtFraseConfirmacion;
	
	private Status status;
	private AfiliacionView view;
	
	public AfiliacionNueva(AfiliacionView view) {
		this.view = view;
	}
	
	private AsyncCallback<Operation> callback = new AsyncCallback<Operation>() {

		@Override
		public void onFailure(Throwable caught) {}

		@Override
		public void onSuccess(Operation result) {
			status.setText((result.isSuccess())?"Correcto":"Error");
			if(result.isSuccess())
				MessageBox.info("Nuevo", "La afiliaci&oacute;n se guard&oacute; correctamente", new Listener<MessageBoxEvent>() {
					
					@Override
					public void handleEvent(MessageBoxEvent be) {
						close();
					}
				});
			else
				MessageBox.info("Nuevo", result.getMessage(), null);
			
		}
		
		
	};
	
	private void close(){
		view.closeAndBack(this);
	}
	
	private void submit(){
		
		boolean success = true;
		List<Field<?>> fields = form.getFields();
		for(Field<?> f : fields){
			
			if(! f.isValid() ){
				success = false;
				status.setText(f.getErrorMessage());
			}
			
		}
		
		if( !txtFrase.getValue().equals(txtFraseConfirmacion.getValue()) ){
			status.setText("La frase y la confirmaci&oacute;n de la misma no coinciden.");
			success = false;
		}
		
		
		if(success){

			Afiliacion afiliacion = new Afiliacion();
			afiliacion.setCuenta(cboCuenta.getValue());
			afiliacion.setNrocel(numCelular.getValue().toString());
			afiliacion.setFrase(txtFrase.getValue());
			
			service.save(afiliacion, callback);
			
		}
		
		
		
		
		
	}


	
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		
		setLayout(new FitLayout());
		contentPanel = new ContentPanel();
		contentPanel.setHeaderVisible(false);
		contentPanel.setBorders(false);
		contentPanel.setBodyBorder(false);
		ToolBar toolBar = createToolBar();
		contentPanel.setTopComponent(toolBar);
		
		ToolBar statusBar = new ToolBar();
		status = new Status();
		statusBar.add(status);
		contentPanel.setBottomComponent(statusBar);
		
		vp = new VerticalPanel();
		vp.setSpacing(10);
		createForm();
		
		contentPanel.add(vp);
		add(contentPanel);
	}

	private ToolBar createToolBar(){
		
		ToolBar toolBar = new ToolBar();
		
		toolBar.add(new LabelToolItem("Afiliaci&oacute;n Nueva"));
	    toolBar.add(new SeparatorToolItem());
		
		toolBar.add(new Button("Guardar",  new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				submit();
			}

		}));
		
		toolBar.add(new Button("Regresar", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				close();
			}
			
		}));

		return toolBar;
	}
	

	private void createForm() {
	
		FormData formData = new FormData("-20");
		form = new FormPanel();
		form.setFrame(true);
		form.setIcon(Resources.ICONS.form());
		form.setHeading("Nueva Afiliaci&oacute;n");
		form.setSize(400, -1);
		form.setLabelWidth(100);
		form.setButtonAlign(HorizontalAlignment.CENTER);
		
		// Nro Cuenta 
		RpcProxy<ListLoadResult<Cuenta>> proxy = new RpcProxy<ListLoadResult<Cuenta>>() {
			
			@Override
			protected void load(Object loadConfig,
					AsyncCallback<ListLoadResult<Cuenta>> callback) {
				service.getCuentas(callback);
			}
			
		};
		
		ListLoader<ListLoadResult<BeanModel>> loader = new BaseListLoader<ListLoadResult<BeanModel>>(proxy);
		ListStore<Cuenta> store = new ListStore<Cuenta>(loader);
		loader.load(null);
		
		cboCuenta = new ComboBox<Cuenta>();
		cboCuenta.setFieldLabel("Nro Cuenta");
		cboCuenta.setEmptyText("Seleccionar...");
		cboCuenta.setLoadingText("Cargando...");
		cboCuenta.setDisplayField(Cuenta.DESCRIPCION); 
		cboCuenta.setValueField(Cuenta.CUENTA);
		cboCuenta.setStore(store);
		cboCuenta.setTypeAhead(true);
		cboCuenta.setForceSelection(true); 
		cboCuenta.setTriggerAction(TriggerAction.ALL); 
		cboCuenta.setAllowBlank(false);
		form.add(cboCuenta, formData);

		
		// Nro de Celular
		numCelular = new NumberField();
		numCelular.setFieldLabel("Celular");
		numCelular.setValue(null);
		numCelular.setEmptyText("Num. Celular");
		numCelular.setMaxLength(9);
		numCelular.setAllowBlank(true);
		numCelular.setAllowDecimals(false);
		numCelular.setAllowNegative(false);
		numCelular.setAutoValidate(true);
		form.add(numCelular, formData);

		
		// Nombre corto 
		txtFrase = new TextField<String>();
		txtFrase.setFieldLabel("Frase");
		txtFrase.setAllowBlank(false);
		txtFrase.setPassword(true);
		txtFrase.setMinLength(6);
		txtFrase.setMaxLength(25);
		form.add(txtFrase, formData);
		
		// Descripcion 
		txtFraseConfirmacion = new TextField<String>();
		txtFraseConfirmacion.setFieldLabel("Confirmar Frase");
		txtFraseConfirmacion.setAllowBlank(false);
		txtFraseConfirmacion.setPassword(true);
		txtFraseConfirmacion.setMinLength(6);
		txtFraseConfirmacion.setMaxLength(25);
		form.add(txtFraseConfirmacion, formData);

		form.addButton(new Button("Guardar", new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				submit();
			}
		}));
		
		form.addButton(new Button("Regresar", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				close();
			}
		}));
		
		form.setButtonAlign(HorizontalAlignment.CENTER);
		

		vp.add(form);
	}

}